package com.yanqu.road.server.gameplayer.module.player;

import com.yanqu.road.entity.activity.args.ConditionTypeValueArgs;
import com.yanqu.road.entity.config.beauty.BeautyInfo;
import com.yanqu.road.entity.decoration.DecorationSimple;
import com.yanqu.road.entity.decoration.UserMammonOfflineAdd;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.config.player.UserDecorationInfoResult;
import com.yanqu.road.entity.estatewar.palace.UserPalaceData;
import com.yanqu.road.entity.log.LogDecoration;
import com.yanqu.road.entity.player.UserDecorationOrigin;
import com.yanqu.road.logic.bussiness.player.UserDecorationBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.DecorationPb;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.player.DecorationInfo;
import com.yanqu.road.entity.player.UserBeauty;
import com.yanqu.road.entity.player.UserDecoration;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.skin.SkinModule;
import com.yanqu.road.server.manger.ConfigMgr;
import com.yanqu.road.server.manger.config.BeautyMgr;
import com.yanqu.road.server.manger.DecorationMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.mammon.MammonMgr;
import com.yanqu.road.server.manger.monopolymarket.MonopolyMarketMgr;
import com.yanqu.road.server.manger.palace.PalaceActivity;
import com.yanqu.road.server.manger.palace.PalaceActivityMgr;
import com.yanqu.road.server.manger.systemgroup.newmonopolymarket.NewMonopolyMarketMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DecorationModule extends GeneralModule {

    private Map<Integer, UserDecoration> userDecorationMap;

    private Map<Integer, UserDecorationOrigin> userDecorationOriginMap;

    public DecorationModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        userDecorationMap = UserDecorationBussiness.getUserDecorationMap(player.getUserId());
        userDecorationOriginMap = UserDecorationBussiness.getUserDecorationOriginMap(player.getUserId());
        checkDefaultDecoration();
        MammonMgr.setUserDecoration(player.getUserId(), userDecorationMap);
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public boolean saveData() {
        for(UserDecoration userDecoration : userDecorationMap.values()){
            if(userDecoration.isInsertOption()){
                UserDecorationBussiness.addUserDecoration(userDecoration);
            }else if(userDecoration.isUpdateOption()){
                UserDecorationBussiness.updateUserDecoration(userDecoration);
            }
        }
        for(UserDecorationOrigin origin : userDecorationOriginMap.values()){
            if(origin.isInsertOption()){
                UserDecorationBussiness.addUserDecorationOrigin(origin);
            }else if(origin.isUpdateOption()){
                UserDecorationBussiness.updateUserDecorationOrigin(origin);
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {
        syncUserDecoration(new ArrayList<>(userDecorationMap.values()), true);
        MammonMgr.syncCrossMammonDecoration(new ArrayList<>(userDecorationMap.values()));

        //统计离线财神成就
        UserMammonOfflineAdd userMammonOfflineAdd = MammonMgr.getUserMammonOfflineAdd(player.getUserId());
        if(userMammonOfflineAdd != null){
            Map<Integer, Integer> map = null;
            synchronized (userMammonOfflineAdd){
                if(userMammonOfflineAdd.getCountMap().size() > 0){
                    map = userMammonOfflineAdd.getCountMap();
                    userMammonOfflineAdd.setCountMap(new HashMap<>());
                }
            }
            if(map != null){
                for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                    addMammonCountCondition(entry.getKey(), entry.getValue());
                }
            }
        }
    }

    @Override
    public void loginSendMsg() {

    }

    private void checkDefaultDecoration(){
        List<DecorationInfo> freeDecorationList = DecorationMgr.getFreeDecorationList(player.getUserInfo().getSex());
        for(DecorationInfo decorationInfo : freeDecorationList){
            if(!userDecorationMap.containsKey(decorationInfo.getId())){
                UserDecoration userDecoration = initUserDecoration(decorationInfo.getId(), 0);
                userDecorationMap.put(userDecoration.getDecorationId(), userDecoration);
            }
        }
    }

    /**
     * 后台增加跨服财神称号
     */
    public void consoleAddCrossMammonDecoration(int decorationId, String serverList){
        addDecoration(decorationId, eLogMoneyType.GM, eLogMoneyType.GmSend, 0);
        setServerIds(decorationId, 0, serverList);
    }

    public void addDecoration(int decorationId, long count, eLogMoneyType master, eLogMoneyType son){
        for(int i = 0; i < count; i++){
            addDecoration(decorationId, master, son, 0);
        }
    }

    /**
     * 添加饰品
     *
     * @param fixAddTime 单位秒，增加固定时间，0表示不使用该参数
     */
    private void addDecoration(int decorationId, eLogMoneyType master, eLogMoneyType son, long fixAddTime) {
        boolean isIceServer = ConfigMgr.isTargetSpecialServer(eSpecialServerType.IceServer);
        if (!isIceServer) {
            if (GameConfig.ICE_SERVER_PLAYER_DEC_KEY.contains(String.valueOf(decorationId))) {
                return;
            }
        }
        UserDecoration userDecoration = getUserDecoration(decorationId);
        long oldTime = 0;
        long addTime = 0;
        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(decorationId);
        long param = goodsInfo.getParamList().get(0).longValue();

        // 判断增加时长
        if (fixAddTime != 0) {
            addTime = fixAddTime;
        } else if (-1 != param) {
            addTime = param * DateHelper.MINUTE_SECONDS;
        }

        if(null == userDecoration){
            userDecoration = initUserDecoration(decorationId, fixAddTime);
            userDecorationMap.put(decorationId, userDecoration);
        }else {
            oldTime = userDecoration.getEndTime();
            long nowTime = System.currentTimeMillis() / 1000;
            if (-1 == param) {
                userDecoration.setEndTime(0);
                userDecoration.setModifyTime(nowTime);
            } else {
                long beginTime = nowTime;
                if (userDecoration.getEndTime() > nowTime) {
                    beginTime = userDecoration.getEndTime();
                }
                userDecoration.setEndTime(beginTime + addTime);
                userDecoration.setModifyTime(nowTime);
            }
        }

        addNewChatTitleCheck(decorationId);

        // 财神成就
        int mammonType = MammonMgr.getMammonType(goodsInfo.getGoodsId());
        if (mammonType > 0) {
            addMammonCountCondition(mammonType, 1);
        }

        MammonMgr.addUserDecoration(userDecoration);       //添加到检测管理
        MammonMgr.syncCrossMammonDecoration(userDecoration);   //跨服财神逻辑
        syncUserDecoration(userDecoration);

        MonopolyMarketMgr.addNeedUploadUserInfo(player);
        NewMonopolyMarketMgr.addNeedUploadUserInfo(player);
        syncPalaceDecoration(decorationId);
        AutoLogMgr.add(new LogDecoration(player.getUserId(), decorationId, oldTime, userDecoration.getEndTime(), addTime, master.getValue(), son.getValue()));
    }


    public void syncUserDecoration(UserDecoration userDecoration){
        if(null != userDecoration) {
            List<UserDecoration> syncList = new ArrayList<>();
            syncList.add(userDecoration);
            syncUserDecoration(syncList, false);
        }
    }

    public void syncUserDecoration(List<UserDecoration> userDecorationList, boolean isLogin){
        if(isLogin){
            player.sendPacket(Protocol.U_DECORATION_LIST, DecorationPb.parseDecorationListMsg(userDecorationList));
        }else {
            player.sendPacket(Protocol.U_DECORATION_SYNC, DecorationPb.parseDecorationListMsg(userDecorationList));
        }
    }

    public boolean hasDecoration(int type, int decorationId){
        List<Integer> decorationIdList = getDecorationIdList(type);
        return decorationIdList.contains(decorationId);
    }

    public UserDecoration getUserDecoration(int decorationId){
        return userDecorationMap.get(decorationId);
    }


    public List<Integer> getDecorationIdList(int type){
        List<Integer> dataList = new ArrayList<>();
        long nowTime = System.currentTimeMillis() / 1000;
        for(UserDecoration userDecoration : userDecorationMap.values()){
            DecorationInfo decorationInfo = DecorationMgr.getDecorationInfo(userDecoration.getDecorationId());
            if(decorationInfo != null && decorationInfo.getType() == type){
                if(decorationInfo.isFree()){
                    dataList.add(userDecoration.getDecorationId());
                }else {
                    if(userDecoration.getEndTime() > nowTime || 0 == userDecoration.getEndTime() ){
                        dataList.add(userDecoration.getDecorationId());
                    }
                }
            }
        }
        if(eDecorationType.HeadIcon.getValue() == type){
            //增加解锁门客的头像
            Map<Integer, UserPatrons> patronsMap = player.getModule(PatronsModule.class).getUserPatronsMap();
            for (UserPatrons userPatrons : patronsMap.values()) {
                dataList.add(userPatrons.getPatronsId());
            }
            //增加解锁美女的头像
            Map<Integer, UserBeauty> beautyMap = player.getModule(BeautyModule.class).getBeautyMap();
            for (UserBeauty userBeauty : beautyMap.values()) {
                if (BeautyMgr.isUserBeautyExist(userBeauty)) {
                    dataList.add(userBeauty.getBeautyId());
                    BeautyInfo beautyInfo = BeautyMgr.getBeautyInfo(userBeauty.getBeautyId());
                    if(null != beautyInfo && beautyInfo.getGenderSwapId() > 0){
                        dataList.add(beautyInfo.getGenderSwapId());
                    }
                }
            }
            dataList.addAll( player.getModule(SkinModule.class).getHeadIconIdList());
        }else if(eDecorationType.Costume.getValue() == type){
            dataList.addAll(player.getModule(SkinModule.class).getMainRoleSkinIdList());
            dataList.addAll(player.getModule(SkinModule.class).getLTPMainRoleSkinIdList());
        }
        return dataList;
    }

    /**
     * @param fixAddTime 单位秒，增加固定时间，0表示不使用该参数
     */
    private UserDecoration initUserDecoration(int decorationId, long fixAddTime) {
        DecorationInfo decorationInfo = DecorationMgr.getDecorationInfo(decorationId);
        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(decorationId);
        UserDecoration userDecoration = new UserDecoration();
        userDecoration.setUserId(player.getUserId());
        userDecoration.setDecorationId(decorationInfo.getId());
        long param = goodsInfo.getParamList().get(0).longValue();
        long nowTime = System.currentTimeMillis() / 1000;

        // 设置时间
        if (fixAddTime != 0) {
            userDecoration.setEndTime(nowTime + fixAddTime);
        } else if (-1 != param) {
            userDecoration.setEndTime(nowTime + param * DateHelper.MINUTE_SECONDS);
        }

        userDecoration.setModifyTime(nowTime);
        userDecoration.setInsertOption();
        return userDecoration;
    }

    public Map<Integer, UserDecoration> getUserDecorationMap() {
        return userDecorationMap;
    }

    public UserDecorationOrigin getDecorationOrigin(int decorationId) {
        return userDecorationOriginMap.get(decorationId);
    }
    public void addDecorationOrigin(UserDecorationOrigin data) {
        userDecorationOriginMap.put(data.getDecorationId(), data);
    }

    public void setServerIds(int decorationId, int activityId, String serverIds) {
        if (StringUtils.isNullOrEmpty(serverIds) && activityId == 0) {
            return;
        }
        UserDecorationOrigin decorationOrigin = getDecorationOrigin(decorationId);
        if (decorationOrigin != null) {
            decorationOrigin.setServerIds(serverIds);
            decorationOrigin.setActivityId(activityId);
        } else {
            decorationOrigin = new UserDecorationOrigin();
            decorationOrigin.setUserId(player.getUserId());
            decorationOrigin.setDecorationId(decorationId);
            decorationOrigin.setServerIds(serverIds);
            decorationOrigin.setActivityId(activityId);
            decorationOrigin.setInsertOption();
            addDecorationOrigin(decorationOrigin);
        }

    }

    public List<Long> getServerIds(int decorationId) {
        UserDecorationOrigin decorationOrigin = getDecorationOrigin(decorationId);
        if (decorationOrigin == null) {
            return null;
        }
        String[] split = decorationOrigin.getServerIds().split(",");
        List<Long> ids = new ArrayList<>();
        for (String s : split) {
            ids.add(Long.valueOf(s));
        }
        return ids;
    }

    public int getActivityId(int decorationId) {
        UserDecorationOrigin decorationOrigin = getDecorationOrigin(decorationId);
        if (decorationOrigin == null) {
            return 0;
        }
        return decorationOrigin.getActivityId();
    }

    /**
     * 获取称号类型
     *
     * @return 枚举eHonoraryTitleType
     */
    public int getHonoraryTitleType(int honoraryTitleId) {
        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(honoraryTitleId);
        List<Integer> list = StringUtils.stringToIntegerList(goodsInfo.getExtendParam(), "\\|");
        if (list.size() < 8) {
            return 0;
        }
        return list.get(7);
    }

    /**
     * 当前玩家最高称号阶级
     */
    public int getUserMaxDecorationClass() {
        List<Integer> decorationIdList = getDecorationIdList(eDecorationType.HonoraryTitle.getValue());
        return GoodsMgr.getUserDecorationClass(decorationIdList);
    }


    /**
     * 获取称号过期时间
     * @param decorationId
     * @return
     */
    public long getDecorationOverTime(int decorationId) {
        //0表示永不过期
        long decorationOverTime = -1;
        if(decorationId > 0){
            UserDecoration userDecoration = getUserDecoration(decorationId);
            decorationOverTime = userDecoration.getEndTime();
        }
        return decorationOverTime;
    }


    /**
     * 获取玩家当前穿戴的最高称号信息
     * @return
     */
    public UserDecorationInfoResult getCurMaxDecorationInfo(){
        UserDecorationInfoResult result = new UserDecorationInfoResult();
        List<Integer> decorationIdList = StringUtils.stringToIntegerList(player.getUserInfo().getDecoration(), DecorationMgr.SPLIT_SEPARATOR);
        //最高称号阶级
        result.decorationClass = GoodsMgr.getUserDecorationClass(decorationIdList);
        //最高称号ID
        result.decorationId = GoodsMgr.getUserDecorationMaxLevel(decorationIdList);
        //过期时间
        result.decorationOverTime = getDecorationOverTime(result.decorationId);
        return result;
    }

    /**
     * 添加财神数量成就进度
     */
    private void addMammonCountCondition(int mammonType, int addCount) {
        if (mammonType == eMammonType.HolyMammon.getValue()) {

            player.getModule(AttributeModule.class).addAttributeNoSync(ePlayerAttrType.HolyMammonGetCount, addCount); // 记录下圣灵加成次数，备用
            // 圣灵：给其他所有财神+1 现在统一读取更新
            player.getModule(MammonModule.class).updateAllMammonTask();

        } else {
            // 其他财神：正常加咯
            player.getModule(MammonModule.class).addMammonDecoration(mammonType, addCount);
        }
    }

    /**
     * 添加限时头像
     */
    public void addTimeLimitHead(int goodsId, long count, eLogMoneyType master, eLogMoneyType son) {
        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
        if (goodsInfo == null) {
            log.error("userId {}, goodsId {}, count {}, son {}, can not find goodsInfo!", getUserId(), goodsId, count, son.getValue());
            return;
        }
        int decorationId = goodsInfo.getParamList().get(0).intValue();
        int day = goodsInfo.getParamList().get(1).intValue();
        long time = DateHelper.DAY_SECONDS * day * count;
        addDecoration(decorationId, master, son, time);
    }

    /**
    * 描述：获取称号列表
    * 作者：zrq
    * 时间：2022/2/24
    * 参数：

    * 返回值：
    **/
    public List<DecorationSimple> getHonoraryTitleDecorationSimpleList(){
        int type = eDecorationType.HonoraryTitle.getValue();
        List<DecorationSimple> dataList = new ArrayList<>();
        long nowTime = System.currentTimeMillis() / 1000;
        for(UserDecoration userDecoration : userDecorationMap.values()){
            DecorationInfo decorationInfo = DecorationMgr.getDecorationInfo(userDecoration.getDecorationId());
            if(null == decorationInfo){
                log.error("getHonoraryTitleDecorationSimpleList DecorationInfo not find,userId:{},decorationId:{}", player.getUserId(), userDecoration.getDecorationId());
                continue;
            }
            if(decorationInfo.getType() == type){
                if(decorationInfo.isFree()){
                    DecorationSimple data = new DecorationSimple();
                    data.setDecorationId(userDecoration.getDecorationId());
                    data.setEndTime(0);
                    dataList.add(data);
                }else {
                    if(userDecoration.getEndTime() > nowTime || 0 == userDecoration.getEndTime() ){
                        DecorationSimple data = new DecorationSimple();
                        data.setDecorationId(userDecoration.getDecorationId());
                        data.setEndTime(userDecoration.getEndTime());
                        dataList.add(data);
                    }
                }
            }
        }
        return dataList;
    }

    /**
    * 描述：称号变更同步到跨服
    * 作者：zrq
    * 时间：2022/2/24
    * 参数：

    * 返回值：
    **/
    private void syncPalaceDecoration(int decorationId){
        DecorationInfo decorationInfo = DecorationMgr.getDecorationInfo(decorationId);
        if (decorationInfo.getType() == eDecorationType.HonoraryTitle.getValue()) {//称号变更
            PalaceActivity palaceActivity = PalaceActivityMgr.getInTimePalaceActivity();
            if (null != palaceActivity) {
                UserPalaceData userPalaceData = palaceActivity.getUserPalaceData(player.getUserId());
                if (null != userPalaceData) {
                    palaceActivity.syncDecorationSimple(player);
                }
            }
        }
    }

    public void addNewChatTitleCheck(int decorationId) {
        DecorationInfo decorationInfo = DecorationMgr.getDecorationInfo(decorationId);
        if (decorationInfo == null) {
            return;
        }
        if (decorationInfo.getType() != eDecorationType.ChatTitle.getValue()) {
            return;
        }
        //获得聊天称号时如果没有佩戴聊天称号,要自动装配。
        boolean isTitleOn = false;
        List<Integer> decorationIdList = StringUtils.stringToIntegerList(player.getUserInfo().getDecoration(), DecorationMgr.SPLIT_SEPARATOR);
        for (Integer onId : decorationIdList) {
            DecorationInfo onDecorationInfo = DecorationMgr.getDecorationInfo(onId);
            if (onDecorationInfo == null) {
                continue;
            }
            if (onDecorationInfo.getType() != eDecorationType.ChatTitle.getValue()) {
                continue;
            }
            isTitleOn = true;
            break;
        }
        if (!isTitleOn) {
            player.getModule(PlayerModule.class).changeDecoration(eDecorationType.ChatTitle.getValue(), decorationId, false);
        }
    }
}
